<?php

namespace app\admin\widget;

use think\Controller;

class Field extends Controller
{
    public function read($field, $vo_list)
    {
        $vo_list = json_decode($vo_list, true);

        if (isset($vo_list[$field['field_code']])) {
            $vo = $vo_list[$field['field_code']];
        } else {
            return '';
        }

        $field_type = false;
        if ($vo['field_type'] == $field['field_type']) {
            $field_type = $field['field_type'];
        }

        if ($field_type == 'input') {
            return $vo['value'];
        }
        if ($field_type == 'textarea') {
            return $vo['value'];
        }
        if ($field_type == 'input-date') {
            return $vo['value'];
        }
        if ($field_type == 'radio') {
            return $vo['value'];
        }
        if ($field_type == 'checkbox') {
            return $vo['value'];
        }
        if ($field_type == 'select') {
            return $vo['value'];
        }
        if ($field_type == 'image-upload') {
            return $vo['value'];
        }
        if ($field_type == 'image-upload-multiple') {
            return $vo['value'];
        }
        if ($field_type == 'video-upload') {
            return $vo['value'];
        }
    }

    public function edit($field, $vo_list = null)
    {
        $this->assign('field', $field);

        $field_param = array_filter(explode(PHP_EOL, $field['field_param']));

        $param_list = [];
        foreach ($field_param as $param) {
            if (strpos($param, '=>') != false) {
                list($key, $val) = explode('=>', $param);

                $item['key'] = $key;
                $item['val'] = $val;

                $param_list[] = $item;
            }
        }

        $this->assign('param_list', $param_list);

        $value = '';
        if (!is_null($vo_list)) {
            if (is_numeric($vo_list)) {
                $value = $vo_list;
            } else {
                $val_list = json_decode($vo_list, true);

                if (!is_null($val_list)) {
                    if (isset($val_list[$field['field_code']])) {
                        $vo = $val_list[$field['field_code']];

                        if ($vo['field_type'] == $field['field_type']) {
                            $value = $vo['value'];
                        }
                    } else {
                        $value = '';
                    }
                } else {
                    $value = $vo_list;
                }
            }
        }

        $this->assign('value', $value);

        $tpl_path = 'field/' . $field['field_type'];
        return $this->fetch($tpl_path);
    }
}
